// import { useMutation } from '@apollo/client';
import {
  Button, Form, Input, ImageUploader, Toast,
} from 'antd-mobile';
import classNames from 'classnames';
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import * as qiniu from 'qiniu-js';
// import { COMMIT_STUDENT_INFO } from '@/graphql/user';
import axios from 'axios';
// import { showFail, showSuccess } from '../../utils';
// import { useUserContext } from '@/hooks/userHooks';
// import { useUploadOSS } from '@/hooks/useUpload';
// import { IStudent } from '@/utils/type';
import style from './index.module.less';

const EditInfo = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  // const [store, setStore] = useState({
  //   tel: "13403208655",
  //   name: "Google",
  //   desc: "爷笑了~",
  //   avatar: "/public/avatar.jpg",
  // });
  const list = JSON.parse(localStorage.getItem("Student") as string)[0];
  useEffect(() => {
    if (!list?.tel) return;
    form.setFieldsValue({
      tel: list.tel,
      name: list.name,
      desc: list.desc,
      avatar: [
        {
          url: list.avatar,
        },
      ],
    });
  }, [list]);

  // 更换学员头像
  const uploadHandler = async (file: File) => {
    const result = await axios.get('http://127.0.0.1:3000/upload/uploadToken');
    const token = result.data.data;
    const key = `avatar/${file.name}`;
    const putExtra = {
      fname: key,
    };
    const config = {
      useCdnDomain: true,
      region: qiniu.region.z1,
    };
    const observable = qiniu.upload(file, key, token, putExtra, config);
    let path = list.avatar;
    const observer = {
      next(res: unknown) {
        // 展示进度
        console.log(res);
      },
      error(err: unknown) {
        // 上传错误触发
        console.log(err, 'err');
      },
      complete(res: { key: unknown; }) {
        // 上传成功后
        console.log(res, 'res--上传成功后');
        path = `http://s4o51m5d5.hb-bkt.clouddn.com/${res.key}`;

        // 更新本地存储
        localStorage.setItem(
          'Student',
          JSON.stringify([{ ...list, avatar: path }]),
        );

        // const newList = { ...list };
        // newList.avatar = path;
        // setList(newStore);

        form.setFieldValue('avatar', [{ url: path }]);
      },
    };
    observable.subscribe(observer);
    return Promise.resolve({ url: path });
  };
  // 提交表单
  const onClickHandler = async (value: { name: unknown; tel: unknown; avatar: { url: unknown; }[]; }) => {
    const body = {
      id: list.id,
      name: value.name,
      tel: value.tel,
      avatar: value.avatar[0].url,
    };
    const { data } = await axios.post('http://localhost:3000/setUser', body);
    localStorage.setItem('Student', JSON.stringify(data.data));
    if (data.code === 200) {
      navigate('/my');
      Toast.show({
        content: data?.message,
      });
    }
  };

  return (
    <div className={style.container}>
      <div className={style.logo}>
        <img
          src="https://water-drop-assets.oss-cn-hangzhou.aliyuncs.com/images/henglogo.png"
          alt=""
        />
      </div>
      <Form
        form={form}
        className={classNames(style.form, style.formPadding)}
        onFinish={onClickHandler}
        footer={(
          <Button block type="submit" color="primary" size="large">
            提交
          </Button>
        )}
      >
        <Form.Header>请提交个人信息，都是必填的</Form.Header>
        <Form.Item
          name="name"
          label="昵称"
          rules={[
            {
              required: true,
            },
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name="tel"
          label="手机号"
          rules={[
            {
              required: true,
            },
          ]}
        >
          <Input type="number" />
        </Form.Item>
        <Form.Item name="avatar" label="头像">
          <ImageUploader maxCount={1} upload={uploadHandler} />
        </Form.Item>
      </Form>
    </div>
  );
};

export default EditInfo;
